import React from 'react'
import { Picker, List, DatePicker, InputItem } from 'antd-mobile'
import { createForm } from 'rc-form'
import trial from '../trial'

let minDate1 = new Date()
minDate1.setDate(minDate1.getDate() + 1)
let maxDate1 = new Date()
maxDate1.setMonth(maxDate1.getMonth() + 1)

class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      dataSource: [],
      factorParams: {}
    }
  }
  componentDidMount () {
    this.requestTrialData()
  }

  requestTrialData () {
    T.fetchFusion({
      url: '/fusion/channel-goods/getTrialFactors',
      data: { channelGoodsId: T.urlQuery('channelGoodsId') },
      loading: true
    }).then((res) => {
      if (res.data) {
        let arr = res.data
        let factorParams = {}
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].items) {
            for (var j = 0; j < arr[i].items.length; j++) {
              arr[i].items[j] = { label: arr[i].items[j].text, value: arr[i].items[j].value }
            }
          }
          if (arr[i].isDisplay == 2) {
            factorParams = Object.assign(factorParams, { [arr[i].customizeCode]: arr[i].defaultValue })
          }
          if (arr[i].isDisplay == 1) {
            if (arr[i].displayType == 2 && arr[i].items) {
              factorParams = Object.assign(factorParams, { [arr[i].customizeCode]: [arr[i].items[0].value] })
            }
            if (arr[i].displayType == 1 || arr[i].displayType == 6) {
              factorParams = Object.assign(factorParams, { [arr[i].customizeCode]: 1 })
            }
            if (arr[i].displayType == 5) {
              if (arr[i].customizeCode == 'birthday') {
                let today = new Date()
                today.setFullYear(today.getFullYear() - 30)
                factorParams = Object.assign(factorParams, { [arr[i].customizeCode]: today })
              }
              if (arr[i].customizeCode == 'policyEffectDate') {
                factorParams = Object.assign(factorParams, { [arr[i].customizeCode]: minDate1 })
              }
            }
          }
        }
        this.requestPrice(factorParams)
        this.setState({
          dataSource: arr,
          factorParams: factorParams
        })
      }
    })
  }

  submit (name, type, v) { // 每次change
    const obj = { [name]: v }
    const factorParams = Object.assign(this.state.factorParams, obj)
    this.setState({
      factorParams: factorParams
    })
  }

  requestPrice (factorParams) {
    let submitFactorParams = {}
    for (var item in factorParams) {
      Object.assign(submitFactorParams, { [item]: factorParams[item].toString() })
      if (factorParams[item] instanceof Date) {
        Object.assign(submitFactorParams, { [item]: T.formatDate('yyyy-MM-dd', factorParams[item]) + ' 00:00:00' })
      }
    }
    T.sessionStorage.set('calculateVals', JSON.stringify(submitFactorParams))// 试算因子放缓存session
    let params = {
      'channelGoodsId': T.urlQuery('channelGoodsId'), // 渠道商品计划
      'channelPlanId': this.props.id, // 渠道计划ID
      'factorParams': submitFactorParams
    }
    trial.trialPrice(params, this.props.getAmount)
  }

  onChangePicker (name, type, v) {
    this.submit(name, type, v)
    const obj = { [name]: v }
    const factorParams = Object.assign(this.state.factorParams, obj)
    this.requestPrice(factorParams)
  }

  onBlur (name, type, v, customizeDesc) {
    if (type == 6) {
      const reg = /^\+?[1-9][0-9]*$/
      if (!reg.test(v)) {
        T.showError(customizeDesc + '0より大きくする必要がある')
        return
      }
    }
    this.onChangePicker(name, type, v)
  }

  getValue (customizeCode) {
    const factorParams = this.state.factorParams
    let value = null
    if (factorParams && factorParams[customizeCode]) {
      value = factorParams[customizeCode]
    }
    return value
  }

  render () {
    const { getFieldProps } = this.props.form
    const { dataSource } = this.state
    const minDate = new Date()
    const maxDate = new Date()
    minDate.setFullYear(minDate.getFullYear() - 60)
    maxDate.setFullYear(maxDate.getFullYear() - 4)

    return (
      <div>
        <List>
          {dataSource && dataSource.map((item, index) =>
            <div key={index}>
              {(item.isDisplay && item.isDisplay == 1) &&
              <div key={index}>
                {(item.displayType && (item.displayType == 2 || item.displayType == 3)) &&
                <Picker data={item.items} cols={1} {...getFieldProps(item.customizeCode)} name='gender' value={this.getValue(item.customizeCode)} onChange={(v) => this.onChangePicker(item.customizeCode, item.displayType, v)}>
                  <List.Item arrow='horizontal'>{item.customizeDesc}</List.Item>
                </Picker>
                }
                {(item.displayType && item.displayType == 6) &&
                  <InputItem
                    {...getFieldProps(item.customizeCode, {
                      rules: [{
                        pattern: (/^\+?[1-9][0-9]*$/)
                      }]
                    })}
                    type='digit'
                    placeholder={'入力' + item.customizeDesc}
                    className='tar'
                    value={this.getValue(item.customizeCode)}
                    onChange={(v) => this.submit(item.customizeCode, item.displayType, v)}
                    onBlur={(v) => this.onBlur(item.customizeCode, item.displayType, v, item.customizeDesc)}
                  >{item.customizeDesc}</InputItem>
                }
              </div>
              }
              {(item.displayType && item.displayType == 5) &&
                <div>
                  {item.customizeCode == 'policyEffectDate' &&
                  <DatePicker
                    mode='date'
                    title={item.customizeDesc}
                    extra='日付を選択'
                    value={this.getValue(item.customizeCode)}
                    minDate={minDate1}
                    maxDate={maxDate1}
                    onChange={(v) => this.onChangePicker(item.customizeCode, item.displayType, v)}
                  ><List.Item arrow='horizontal'>{item.customizeDesc}</List.Item>
                  </DatePicker>
                  }
                  {item.customizeCode == 'birthday' &&
                  <DatePicker
                    mode='date'
                    title={item.customizeDesc}
                    extra='日付を選択'
                    value={this.getValue(item.customizeCode)}
                    minDate={minDate}
                    maxDate={maxDate}
                    onChange={(v) => this.onChangePicker(item.customizeCode, item.displayType, v)}
                  ><List.Item arrow='horizontal'>{item.customizeDesc}</List.Item>
                  </DatePicker>
                  }
                </div>

              }
            </div>
          )}

        </List>

      </div>)
  }
}

export default createForm()(App)
